package tom.vertx.core.demo05;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetClientOptions;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ZHUFEIFEI
 */
@Slf4j
public class MyTcpClient extends AbstractVerticle {

  private boolean ssl;

  public MyTcpClient() {
  }

  public MyTcpClient(boolean ssl) {
    this.ssl = ssl;
  }

  @Override
  public void start(Promise<Void> startPromise) throws Exception {
    NetClientOptions options = new NetClientOptions()
      //启用ssl, 使用自签名, 自签名只用于开发测试
      .setSsl(this.ssl)
      //信任所有服务器
//      .setTrustAll(true)
      //双向认证, client也要验证服务器,所以需要设置key cert, 单项认证, 客户端不验证服务器,可以不配置
      .setKeyCertOptions(TcpDemo.keyCertOptions())
      //信任证书
      .setTrustOptions(TcpDemo.trustOptions())
      //debug io.netty.handler.logging.LoggingHandler
      .setLogActivity(false)
      .setReconnectAttempts(3)
      .setReconnectInterval(500)
      .setConnectTimeout(1000);
    NetClient client = vertx.createNetClient(options);

    client.connect(8888,"localhost", res -> {
        if (res.succeeded()) {
          startPromise.complete();
          log.info("connected => {}", res.result().remoteAddress());
          res.result().handler(resp -> {
              log.info("receive server response => {}", resp.toString());
          });
          vertx.setPeriodic(3000L, id -> {
            res.result().write(Buffer.buffer("Hello NetServer."), r -> {
              log.info("sent {}", r.succeeded());
            });
          });
        } else {
          startPromise.fail(res.cause());
          log.info("connect failed => {}", res.cause().toString());
        }
    });

  }


  public static void main(String[] args) {
  }

}
